import { getCollection } from '@/service/collection';
import { AddTagParams, ITag, UpdateTagParams } from '@/service/types';
import { pick } from 'lodash-es';

export const roleCollection = getCollection<ITag>('uni-id-tag');

const fields = ['tagid', 'name', 'description'];

const existTag = async (tagid: string) => {
	try {
		const res = await roleCollection.where({ tagid }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};

const existTagById = async (id: string) => {
	try {
		const res = await roleCollection.where({ _id: id }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};
const getAllTag = async () => {
	try {
		const res = await roleCollection.get();
		return res.data;
	} catch (error) {
		throw error;
	}
};

const getPaginationTag = async (params: PaginationParams) => {
	try {
		const res = await roleCollection
			.where(params.query ? params.query : {})
			.limit(params.limit)
			.skip(params.skip)
			.get({ getCount: true });
		return res;
	} catch (error) {
		throw error;
	}
};
const addTag = async (data: AddTagParams) => {
	try {
		const exist = await existTag(data.tagid);
		if (exist) {
			throw new Error('标签已存在');
		}

		const pickData = pick(data, fields);

		const res = await roleCollection.add(pickData);
		return res.id;
	} catch (error) {
		throw error;
	}
};

const updateTag = async (data: UpdateTagParams) => {
	const exist = await existTagById(data._id);
	if (!exist) {
		throw new Error('标签不存在');
	}
	const pickData = pick(data, fields);
	try {
		const res = await roleCollection
			.where({
				_id: data._id,
			})
			.update(pickData);
		return res.updated;
	} catch (error) {
		throw error;
	}
};

const deleteTag = async (id: string) => {
	try {
		const res = await roleCollection.where({ _id: id }).remove();
		return res.deleted;
	} catch (error) {
		throw error;
	}
};
export const tag = {
	getAllTag,
	addTag,
	updateTag,
	getPaginationTag,
	deleteTag,
};
